package com.useeinfo.oa.modules.logger.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.oa.modules.logger.entity.FacilityLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("facilityLogDao")
public class FacilityLogDao implements CrudDao<FacilityLog> {
    private final static Logger logger = LoggerFactory.getLogger(FacilityLogDao.class);

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from FacilityLog s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<FacilityLog> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from FacilityLog s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<FacilityLog> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, FacilityLog.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public FacilityLog findModel(Long id) {
        return entityManager.find(FacilityLog.class, id);
    }

    @Override
    public Integer add(FacilityLog model) {
        model.setCreateDate(new Date());
        entityManager.persist(model);
        logger.info("FacilityLogDaoImpl添加areaInfo成功！");
        return 1;
    }

    @Override
    public Integer update(FacilityLog model) {
        model.setUpdateDate(new Date());
        entityManager.merge(model);
        return 1;
    }

    @Override
    public Integer delete(Long id) {
        FacilityLog area = entityManager.find(FacilityLog.class, id);
        entityManager.remove(area);
        return 1;
    }

    @Override
    public Integer deleteLogic(FacilityLog model) {
        model.setDeleteStatus(true);
        return 1;
    }
}
